<template>
    <div class="table-wrapper ui segment">
        <div>
            <div class="ui grid">
                <div class="eight wide column">
                    <div class="ui checkbox slider" v-show="tableHide&&linesNew.length>0" v-if="checkType=='checkbox'">
                        <input type="checkbox" name="is_all" value="1" v-model="is_all">
                        <label for="">全选</label>
                    </div>
                    <div class="ui label icon tiny tableHide" @click.stop.prevent="tableHide=!tableHide">{{tableHideStr}}<i
                        class="icon big"
                        :class="{'toggle off':tableHide,'toggle on':!tableHide}"></i>
                    </div>

                </div>
                <div class="eight wide column">

                    <mysearch :no_search="no_search" :url="url" :bind_mid="bind_mid" :name="name" @doBindSearch="doBindSearch"
                              @clearSearch="clearSearch"></mysearch>
                </div>
                <div class="sixteen wide column">
                    <div v-if="attrArr" v-for="_id in attrArr" class="ui compact tiny message msgLeft">
                        <span v-show="false">{{myname = lineForname && lineForname[_id] ? lineForname[_id] : `ID:${_id}`}}</span>
                        {{myname}}
                        <i class="icon remove" @click="removeAttrItem(_id)"></i>
                    </div>
                    <fenye @changePage='changePage' class="fenye" :page="page" :pages="pages" :total="total"></fenye>
                </div>
            </div>

            <!--<div v-for="selected in selecteds" class="ui compact tiny message msgLeft">-->
            <!--{{selected}}-->
            <!--</div>-->


        </div>
        <table v-show="tableHide" v-if="linesNew.length>0" class="ui small column striped celled table">
            <thead class="">
            <tr>
                <!-- <th v-for=" title in titles">{{title}}</th> -->
                <th>选择</th>
                <th v-for=" head in firstLine" :class="head.field">{{head.title}}</th>

            </tr>
            </thead>
            <tbody>
            <tr v-for="line in linesNew">
                <td>
                    <input class="lineChk" v-if="checkType=='radio'" type="radio" v-model="attr" :value="line[0].rs"/>
                    <input class="lineChk" v-if="checkType=='checkbox'" type="checkbox" v-model="attr"
                           :value="line[0].rs"/>
                </td>
                <!-- <td v-for="field in fields">
                  {{line[field]}}
                </td> -->
                <td v-for="col in line">
                    <mycell :col="col" :ctl="ctl"></mycell>
                </td>
            </tr>

            </tbody>

        </table>
        <div v-show="tableHide" class="ui segment" v-if="no_data_show">
            <p style="color: black;">没有数据</p>
        </div>
        <div class="ui dimmer inverted" :class="{active:loading}">
            <div class="ui loader text">loading</div>
        </div>
    </div>
</template>

<script>
    import tool from 'src/util/tool';
    import util from '_util/index';
    import mycell from 'components/page/cell'
    import mysearch from 'components/form/search'
    import fenye from 'components/common/fenye';
    import _ from 'lodash';
    import logic from '_logic';

    export default {
        data() {
            return {
                attr: [],
                page: 1,
                myval: null,
                lineForname: null,
                is_all: false,
                tableHide: true,
            }
        },
        components: {
            mycell,
            fenye,
            mysearch
        },
        methods: {
            removeAttrItem(id) {
                if (this.checkType == 'checkbox')
                    this.attr.remove(id)
                else
                    this.attr = ''
            },
            clearSearch() {
//      this.clearAttr()
                this.$emit('clearSearch')
            },
            doBindSearch(url, param) {
//      this.clearAttr()
//        tool.cl(url, param);
                this.$emit('doBindSearch', url, param)
            },
            changePage(page) {
                this.page = page
// this.loadingShow = true
                this.$emit('changePage', page)
            },
            setBindName() {
                let fg = '';
                if (this.bindNames.indexOf('#|#') !== -1)
                    fg = '#|#';
                else
                    fg = '|';
                let names = this.bindNames.split(fg);
                this.lineForname = this.lineForname || {};

                if (Array.isArray(this.attr)){
					this.attr.map((id, ind) => {
						this.lineForname[id] = names[ind];
					});
				}else{
					this.lineForname[this.attr] = names[0];
				}
                this.set_lineForname()
            },
            setAttr() {
                let checkType = this.checkType;

                if (this.myval) {
                    if (checkType == 'checkbox') {
                        if (this.myval instanceof Array) {
                            this.attr = this.attr.concat(this.myval)
                        } else
                            this.attr = [this.myval]
                    } else
                        this.attr = this.myval

                }
            },
            trClick(event) {
                let target = event.target
                if (this.checkType == 'checkbox') {
                    let id = $(target).closest('tr').find('input[type=checkbox]').val()
                    let ind = this.attr.indexOf(id)
                    if (ind != -1) {
                        this.attr.remove(id)
                    } else
                        this.attr.add(id)
                } else {
                    let id = $(target).closest('tr').find('input[type=radio]').val()
                    this.attr = id
                }

            },
            clearAttr() {
                if (this.checkType == 'checkbox')
                    this.attr = []
                else
                    this.attr = ''
            },
            emitBind(tableSelected) {
                let selectedAll = this.$store.state.global.tableSelected;
                selectedAll[this.name] = tableSelected
                util.store.commit(this,'setTableSelected', selectedAll);

                let eventVue = util.store.get(this,'eventVue');
                eventVue.$emit(this.bindStr)
            },
            set_lineForname(){
                this.lineForname = this.lineForname || {};
                this.linesNew.forEach(item => {
                    this.lineForname[item[0].rs] = item[1].rs;
                });
            },
            hl_val(val,need_field){
                let {field} = this.lines[0][0];
//                tool.cl('field:', field);
//                tool.cl('v:', v);

                let fg = '#_#';
                let flag=false;
              if(!util.isArray(val)){
                  val = [val];
                  flag=true;
              }
//                tool.cl('val:', val);
                val=val.map(item => {
                    let tmp=this.lines_all.find(line => {
                        let {field: f1, val: v1} = line[0];
                        return f1 == field&&v1==item;
                    });
//                    tool.cl('tmp:', tmp);
//                    tmp=_.find(tmp, { 'field': need_field});
                    let col_field = [];
                    tmp&&tmp.forEach((col)=> {
                        need_field.contains(col.field) && col_field.push(col.val);
                    })
//                    tool.cl('col_field:', col_field);
                    let rs = col_field.length > 0 ? col_field.join(fg) : '';
                    return `${item}${fg}${rs}`;
                });
              if(flag) {
                  val = val[0];
              }
                return val;
            }
        },
        watch: {
            current_page: function (val, old) {
                if (val!=old) {

                    this.page=val;

                }
            },
            linesNew: function (val, old) {
                if (val) {

                    this.set_lineForname();

                }

            },
            attr: function (val, old) {
                let names = [];

                if (val) {
                    if (util.isArray(this.attr))
                        this.attr.map((id, ind) => {
                            if (this.lineForname)
                                names[ind] = this.lineForname[id]
                        });
                    else {
                        if (this.lineForname)
                            names[0] = this.lineForname[this.attr];
                    }

                }

                if(this.val_field&&val) {
                    val=this.hl_val(val,this.val_field);
                }

                names = names.join('#|#');
                this.$emit('setVal', val, names)
            },
            is_all: function (val, old) {
                if (val) {

                    this.linesNew.forEach((line) => {
                        this.attr.push(line[0].rs)
                    });

                } else {
                    this.attr = [];
                }
            }
        },
        computed: {
            no_data_show() {
                return this.linesNew.length==0&&this.is_search;
            },
            page_ctl() {
                return this.$route.query.ctl;
            },
            val_field() {
                if(this.field&&this.field.bind_val_field) {
                    let val_field=this.field.bind_val_field.split(',');
                    return val_field;
                }
                return null;
            },
            no_search() {
                return this.field?[33].contains(this.field.bindModel):false;
            },
            bind_mid() {
                return this.field ? this.field.bindModel : null;
            },
            tableHideStr() {
                return !this.tableHide ? '显示' : '隐藏'
            },
            pages() {
                let row = tool.BIND_ROW_NUM
                let pages = 0
                if (this.total % row == 0) {
                    pages = this.total / row
                } else
                    pages = Math.floor(this.total / row) + 1
                return pages
            },
            bindStr() {
                return 'setBindVal_' + this.name
            },
            clearAttrStr() {
                return 'clearAttr_' + this.name
            },
            linesNew() {
                if (!util.isArray(this.lines))
                    return []
                let filtered = this.lines.map((line, ind) => {
                    let newl = line.filter(col => {
                        let b = this.fields.includes(col.field) && col.title != '操作'
                        return b;
                    });
                    return newl;
                })
                return filtered;
            },
            firstLine() {
                return this.linesNew[0];
            },
            tableSelected() {
                return this.$store.state.global.tableSelected[this.name];
            },
            attrArr() {
                let tmp = [];
                if (this.checkType == 'checkbox')
                    tmp = this.attr
                else
                    tmp = util.isArray(this.attr) ? [] : [this.attr]
                return tmp.filter(item => item);
            },
        },
        props: ['fields', 'field', 'lines','is_search','current_page', 'loading', 'total', 'url', 'ctl', 'name', 'val', 'checkType', 'data_type', 'bindNames','lines_all'],
        updated() {
        },
        created() {
            this.page = this.current_page || 1;
            let checkType = this.checkType;
            if (checkType == 'checkbox') {
                let val = this.val
                if (val && util.isString(val)) {
                    let arr = null;
//          if(val.indexOf('|')!==-1) {
//            arr = val.split('|');
//          }else{
                    if (this.data_type == 1) {
                        arr = val.split('|');
                    } else {
                        arr = JSON.parse(val);

                    }

                    if (arr instanceof Array) {
                        this.myval = arr;
                    }

                } else if (util.isNumber(val)) {
                    this.myval = [val];
                }

            } else
                this.myval = this.val;
            this.setAttr();
            let op = util.getOp(this);
//            if (this.bindNames && op != 'insert')
            if (this.bindNames )
                this.setBindName();
            let eventVue = util.store.get(this,'eventVue');
            eventVue.$on('clearTable', this.clearAttr)

//            logic.edit.bind_val_field(this);
        }
    };
</script>

<style rel="stylesheet/less" scoped lang="less">
    .table-wrapper {
        .ui.label.icon.tiny.tableHide {
            .icon {
                color: rgba(0, 0, 0, 0.5);
                &:hover {
                    color: rgba(0, 0, 0, 0.8);
                }
            }
        }
        .ui.label {
            cursor: pointer;
            margin-left: 10px;
            i.icon {
                font-size: 2.5em;
                margin-left: 5px;
                margin-right: 0;
                color: rgba(0, 0, 0, 0.6);
            }
        }
        .fenye {
            float: right;
        }
        .lineChk {
            cursor: pointer;
        }
        .tiny.message {
            margin-left: 5px;
            position: relative;
            i {
                color: rgba(0, 0, 0, 0.3);
                cursor: pointer;
                position: absolute;
                top: 0px;
                right: 2px;
                margin-right: 0;
            }
        }
    }
</style>
>
